package com.shujia.map;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapRunnable implements Runnable {

    private String id;
    private File file;

    public MapRunnable(File file, String id) {
        this.file = file;
        this.id = id;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        try {
            //统计班级个数
            //创建字符缓冲输入流
            br = new BufferedReader(new FileReader(file));

            //创建集合对象
            HashMap<String, Integer> map = new HashMap<>();

            String line = null;
            while ((line = br.readLine()) != null) {
                //判断集合中是否存在该班级，如果不存在，说明是第一次添加，value设置为1，如果存在，就将value值取出来+1,重新赋值
                //1500100105,寿白亦,22,女,文科五班
                String clazz = line.split(",")[4];
                if (!map.containsKey(clazz)) {
                    map.put(clazz, 1);
                } else {
                    map.put(clazz, map.get(clazz) + 1);
                }
            }

            //创建字符缓冲输出流对象
            BufferedWriter bw = new BufferedWriter(new FileWriter("hadoop/data/maps/part-m-0000" + id));

            //遍历集合，将每个block块的结果写入到map结果文件中
//            Set<Map.Entry<String, Integer>> entries = map.entrySet();
            map.forEach((k, v) -> {
                try {
                    bw.write(k + " " + v);
                    bw.newLine();
                    bw.flush();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            });

            bw.close();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
